package com.chb.fallback;

import com.alibaba.fastjson.JSON;
import com.chb.common.ResultCode;
import com.chb.dto.ResultDto;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.SocketTimeoutException;

/**
 * @author CHB
 * @createTime 2022-8-25 13:31
 */
@Component
@Slf4j
public class ZuulFallbackProvider implements FallbackProvider {
    @Override
    public String getRoute() {
        // 表明是为哪个微服务提供回退，*表示为所有微服务提供回退
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        Throwable serviceException = cause.getCause();
        log.error("zuul fallback,type:{}:{}",cause.getClass(), serviceException == null ? cause.getMessage() : serviceException.getMessage());
        if(serviceException != null){
            if(serviceException instanceof SocketTimeoutException){
                return response(ResultCode.TIME_OUT_RESPONSE.getCode());
            }
        }
        if (cause instanceof HystrixTimeoutException) {
            return response(ResultCode.TIME_OUT_REQUEST.getCode());
        } else {
            return this.fallbackResponse();
        }
    }

    public ClientHttpResponse fallbackResponse() {
        return this.response(ResultCode.ERROR.getCode());
    }


    private ClientHttpResponse response(final int status) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() {
                return 200;
            }

            @Override
            public String getStatusText() {
                return "OK";
            }

            @Override
            public void close() {
            }

            @Override
            public InputStream getBody() {
                String str = JSON.toJSONString(ResultDto.error(status,ResultCode.getNameByCode(status)));;
                return new ByteArrayInputStream(str.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                // headers设定
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}
